package com.gzyct.m.api.common.sign;

import java.util.Map;
import java.util.TreeMap;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.gzyct.m.api.common.intf.req.InterfaceRequest;
import com.gzyct.m.api.common.intf.resp.InterfaceResp;

public class HttpJsonSignStringBuilder implements SignStringBuilder {

	@Override
	public String requestBuild(InterfaceRequest ir) {
		Map<String, String> requestParam = ir.getRequestParam();
		TreeMap<String, String> signMap = new TreeMap<String, String>();
		signMap.putAll(requestParam);
		signMap.remove(InterfaceRequest.SIGN);
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, String> entry : signMap.entrySet()) {
			if (entry.getValue() != null && !"".equals(entry.getValue())) {
				sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
			}
		}
		return sb.substring(0, sb.length() - 1).toString();
	}

	@Override
	public String respBuild(InterfaceResp ir) {
		Map<String, String> responseParam = ir.getResponseParam();
		TreeMap<String, String> signMap = new TreeMap<String, String>();
		signMap.putAll(responseParam);
		signMap.remove(InterfaceResp.SIGN);
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, String> entry : signMap.entrySet()) {
			if (entry.getValue() != null && !"".equals(entry.getValue())) {
				sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
			}
		}
		return sb.substring(0, sb.length() - 1).toString();
	}

	@Override
	public InterfaceResp updateSign(InterfaceResp ir, String sign) {
		ir.setSign(sign);
		ir.getResponseParam().put(InterfaceResp.SIGN, sign);
		JsonObject obj = (JsonObject) new JsonParser().parse(ir.getResponseBody());
		obj.remove(InterfaceRequest.SIGN);
		obj.addProperty(InterfaceRequest.SIGN, sign);
		ir.setResponseBody(obj.toString());
		return ir;
	}

}
